import { useState, useCallback, useEffect } from 'react';
import { ReactFlowProvider, applyNodeChanges, applyEdgeChanges, addEdge } from '@xyflow/react';
import type { Node, Edge, OnNodesChange, OnEdgesChange, OnConnect } from '@xyflow/react';
import axios from 'axios';
import { useTranslation } from 'react-i18next';

import './App.css';
import NodePanel from './components/NodePanel';
import SettingsPanel from './components/SettingsPanel';
import WorkflowEditor from './components/WorkflowEditor';
import LanguageSwitcher from './components/LanguageSwitcher';

const initialNodes: Node[] = [];

function App() {
  const { t } = useTranslation();
  const [nodes, setNodes] = useState<Node[]>(initialNodes);
  const [edges, setEdges] = useState<Edge[]>([]);
  const [selectedNode, setSelectedNode] = useState<Node | null>(null);

  const onNodesChange: OnNodesChange = useCallback(
    (changes) => setNodes((nds) => applyNodeChanges(changes, nds)),
    [setNodes]
  );

  useEffect(() => {
    const selected = nodes.find(n => n.selected);
    setSelectedNode(selected || null);
  }, [nodes]);

  const onEdgesChange: OnEdgesChange = useCallback(
    (changes) => setEdges((eds) => applyEdgeChanges(changes, eds)),
    []
  );

  const onConnect: OnConnect = useCallback(
    (connection) => setEdges((eds) => addEdge(connection, eds)),
    []
  );

  const onNodeDataChange = (nodeId: string, newData: object) => {
    setNodes((nds) =>
      nds.map((node) => {
        if (node.id === nodeId) {
          return { ...node, data: { ...node.data, ...newData } };
        }
        return node;
      })
    );
    if (selectedNode && selectedNode.id === nodeId) {
      setSelectedNode(prev => prev ? { ...prev, data: { ...prev.data, ...newData } } : null);
    }
  };

  const handleRunWorkflow = useCallback(async () => {
    if (nodes.length === 0) {
      alert('Cannot run an empty workflow.');
      return;
    }
    try {
      const response = await axios.post('http://127.0.0.1:5001/api/v1/workflow/execute', {
        nodes,
        edges,
      });
      alert('Workflow execution started successfully!');
      console.log('Backend response:', response.data);
    } catch (error) {
      console.error('Error executing workflow:', error);
      alert('Failed to start workflow execution. Check the console for details.');
    }
  }, [nodes, edges]);

  // --- NEW --- Function to handle node deletion
  const onNodeDelete = useCallback((nodeId: string) => {
    // Remove the node itself
    setNodes((prevNodes) => prevNodes.filter((n) => n.id !== nodeId));
    // Remove all edges connected to this node
    setEdges((prevEdges) => prevEdges.filter((e) => e.source !== nodeId && e.target !== nodeId));
    // Clear selection
    setSelectedNode(null);
  }, [setNodes, setEdges]);


  return (
    <div className="app-container">
      <header className="app-header">
        <h1>{t('header.title')}</h1>
        <div className="header-controls">
          <LanguageSwitcher />
          <button onClick={handleRunWorkflow} className="run-button">{t('header.runButton')}</button>
        </div>
      </header>
      <main className="main-content">
        <ReactFlowProvider>
          <NodePanel />
          <WorkflowEditor 
            nodes={nodes}
            edges={edges}
            setNodes={setNodes}
            onNodesChange={onNodesChange}
            onEdgesChange={onEdgesChange}
            onConnect={onConnect}
          />
          <SettingsPanel 
            selectedNode={selectedNode}
            onDataChange={onNodeDataChange}
            onNodeDelete={onNodeDelete} // --- NEW --- Pass the delete handler
          />
        </ReactFlowProvider>
      </main>
    </div>
  );
}

export default App;